<template>
  <div class="publishContainer">
    <div class="header">
      <div class="goback" @click="goback">
        <span class="iconfont icon-huitui"></span> 点击回退
      </div>
      <div class="title">
        {{ title }}
      </div>
    </div>
    <div class="from">
      <el-form
        :model="ruleForm"
        :rules="rules"
        ref="ruleForm"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item label="商品名称" prop="goodsname">
          <el-input v-model="ruleForm.goodsname"></el-input>
        </el-form-item>
        <el-form-item label="商品数量" prop="goodsnum">
          <el-input-number
            v-model="ruleForm.goodsnum"
            :min="1"
            :max="10000"
          ></el-input-number>
        </el-form-item>

        <el-form-item label="现价" prop="curprice">
          <el-input-number
            v-model="ruleForm.curprice"
            :min="1"
            :precision="2"
            :step="0.1"
            :max="1000000"
          ></el-input-number>
        </el-form-item>
        <el-form-item label="原价" prop="preprice">
          <el-input-number
            v-model="ruleForm.preprice"
            :min="1"
            :precision="2"
            :step="0.1"
            :max="1000000"
          ></el-input-number>
        </el-form-item>
        <el-form-item label="商品图片">
          <el-upload
            action="#"
            list-type="picture-card"
            :on-change="handleChange"
            :auto-upload="false"
            ref="upload"
          >
            <i slot="default" class="el-icon-plus"></i>
            <div slot="file" slot-scope="{ file }">
              <img
                class="el-upload-list__item-thumbnail"
                :src="file.url"
                alt=""
              />
              <span class="el-upload-list__item-actions">
                <span
                  class="el-upload-list__item-preview"
                  @click="handlePictureCardPreview(file)"
                >
                  <i class="el-icon-zoom-in"></i>
                </span>
                <span
                  class="el-upload-list__item-delete"
                  @click="handleDownload(file)"
                >
                  <i class="el-icon-download"></i>
                </span>
                <span
                  v-if="!disabled"
                  class="el-upload-list__item-delete"
                  @click="handleRemove(file)"
                >
                  <i class="el-icon-delete"></i>
                </span>
              </span>
            </div>
          </el-upload>
          <el-dialog :visible.sync="dialogVisible">
            <img width="100%" :src="dialogImageUrl" alt="" />
          </el-dialog>
        </el-form-item>
        <el-form-item label="联系方式" prop="concatway">
          <el-input v-model="ruleForm.concatway"></el-input>
        </el-form-item>
        <el-form-item label="商品详情" prop="goodsdesc">
          <el-input type="textarea" v-model="ruleForm.goodsdesc"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitForm('ruleForm')"
            >提交</el-button
          >
          <el-button @click="resetForm('ruleForm')">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script>
import { uploadImage, addGoods, updateGoodsData } from "@/utils/api";
export default {
  props: {
    title: String,
    selection: {
      type: Object,
      default: () => ({}),
    },
    optionType: String,
    isShowPublish: Boolean,
  },
  data() {
    return {
      ruleForm: {
        goodsname: "",
        goodsnum: 1,
        goodsdesc: "",
        curprice: 1,
        preprice: 1,
        concatway: "",
      },
      dialogImageUrl: "",
      dialogVisible: false,
      disabled: false,
      goodsimage: [],
      rules: {
        goodsname: [
          { required: true, message: "请输入商品名称", trigger: "blur" },
        ],
        concatway: [
          { required: true, message: "请输入商品名称", trigger: "blur" },
        ],
        goodsnum: [
          { required: true, message: "请输入商品数量", trigger: "change" },
        ],
        curprice: [
          { required: true, message: "请输入商品现价", trigger: "change" },
        ],
        preprice: [
          { required: true, message: "请输入商品原价", trigger: "change" },
        ],
        goodsdesc: [{ required: true, message: "请输入详情", trigger: "blur" }],
      },
    };
  },
  watch: {
    isShowPublish(newVal) {
      if (newVal && this.$props.optionType === "update") {
        this.ruleForm = this.$props.selection;
      }
    },
  },
  computed: {
    uid() {
      return sessionStorage.getItem("uid");
    },
  },
  methods: {
    updateHandle() {
      let that = this;
      let good = JSON.stringify({
        ...that.ruleForm,
        goodsimage: that.goodsimage.join("&"),
        coverimage: that.goodsimage[0],
      });
      updateGoodsData({
        good,
      })
        .then((res) => {
          that.$message.success(res);
          that.$emit("close");
          that.$emit("request");
        })
        .catch((err) => {
          console.log(err);
          that.$message.error(err.message);
        });
    },
    addHandle() {
      let that = this;
      let good = JSON.stringify({
        ...that.ruleForm,
        goodsimage: that.goodsimage.join("&"),
        coverimage: that.goodsimage[0],
        uid: parseInt(that.uid),
      });
      addGoods({
        good,
      })
        .then((res) => {
          that.$message.success(res);
          that.$emit("close");
          that.$emit("request");
        })
        .catch((err) => {
          console.log(err);
          that.$message.error(err.message);
        });
    },
    submitForm(formName) {
      let that = this;
      if (!that.goodsimage.length) {
        that.$message.error("图片未上传，请至少上传一张图片！！");
        return false;
      }
      that.$refs[formName].validate((valid) => {
        if (valid) {
          if (this.$props.optionType === "add") {
            that.addHandle();
          } else if (this.$props.optionType === "update") {
            that.updateHandle();
          }
        } else {
          return false;
        }
      });
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
    goback() {
      this.$emit("close");
    },
    async handleChange(file) {
      console.log(file);
      let fromData = new FormData();
      fromData.append("file", file.raw);
      let url = await uploadImage(fromData);
      this.goodsimage.push(url);
    },
    handleRemove(file) {
      console.log(file);
      let uploadsData = this.$refs.upload.uploadFiles;
      const index = uploadsData.findIndex((item) => item.uid === file.uid);
      this.$refs.upload.uploadFiles.splice(index, 1);
      this.goodsimage.splice(index, 1);
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    handleDownload(file) {
      console.log(file);
    },
  },
};
</script>

<style lang="less" scoped>
.publishContainer {
  background: #fff;
  text-align: left;
  padding-bottom: 20px;
  .header {
    display: flex;

    justify-content: space-between;
    align-items: center;
    .title {
      margin-top: 5px;
      flex: 1;
      text-align: center;
    }
  }
  .goback {
    font-size: 12px;
    color: #409eff;
    cursor: pointer;
    margin-top: 5px;
    .icon-huitui {
      font-size: 12px;
    }
  }
  .from {
    width: 60%;
    margin-top: 10px;
  }
}
</style>